import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, message, DatePicker, Modal } from 'antd';
import React, { useState, useRef } from 'react';
import { useRequest } from '@umijs/hooks';
import ProTable from '@ant-design/pro-table';
import styles from './index.less';
import AuthComponent from '@/components/Authorized/AuthComponent';
import moment from 'moment';
import { useActivate } from 'react-activation';
import ScrapListForm from './components/ScrapListForm'
import ExtendScrapDateTable from './components/ExtendScrapDateTable'
import ScrapDetail from './components/ScrapDetail'
import { scrapPageList, addScrap, deleteScrapLostForm, confirmScrap, closeScrapLostForm } from './service'
import { getImgByRelevance, batchUpdateImg } from '../lostItemForm/service'
import PicUpload from '../lostItemForm/components/PicUpload'
import ShowPic from '../lostItemForm/components/ShowPic'


const LostItemScrapManage = () => {

  // 遗失物品基础信息
  const stateStr = sessionStorage.getItem('/lostItemManage/lostItemDetail');
  const stateObj = stateStr ? JSON.parse(stateStr) : {};

  const actionRef = useRef();
  const ref = useRef()

  // 生成报废清单弹窗显隐
  const [scrapListVisible, handleScrapListVisible] = useState(false)
  // 延长报废时间弹窗显隐
  const [extendScrapDateVisible, handleExtendScrapDateVisible] = useState(false)
  // 多选
  const [selectedRowKeys, handleSelectedRowKeys] = useState([])
  // 编辑报废单编号
  const [scrapNum, handleScrapNum] = useState('')
  // 详情弹窗显隐
  const [scrapDetailVisible, handleScrapDetailVisible] = useState(false)
  // 是否有图片
  const [lostItemPic, handleLostItemPicture] = useState({ goodFileList: [], touristFileList: [], paperFileList: [] })
  // 初始图片数组
  const [originPicArr, handleOriginPicArr] = useState([])
  // 图片上传弹窗显隐
  const [lostItemPicVisible, handleLostItemPicVisible] = useState(false)
  // 图片管理弹窗显隐
  const [lostItemPicManageVisible, handleLostItemPicManageVisible] = useState(false)

  // 删除接口
  const { run: deleteScrapLostFormR } = useRequest(params => deleteScrapLostForm(params), {
    manual: true,
    onSuccess: (res) => {
      message.success('删除成功')
      actionRef.current.reload()
    }
  })
  // 结案接口
  const { run: closeScrapLostFormR } = useRequest(params => closeScrapLostForm(params), {
    manual: true,
    onSuccess: (res) => {
      message.success('结案成功')
      actionRef.current.reload()
    }
  })
  // 遗失物品图片接口
  const { run: getImgByRelevanceR } = useRequest(params => getImgByRelevance(params), {
    manual: true,
    onSuccess: (res) => {
      handleOriginPicArr(res)
      let goodFileListData = res.filter(item => {
        return item.oneType === 1
      })

      let touristFileListData = res.filter(item => {
        return item.oneType === 2
      })

      let paperFileListData = res.filter(item => {
        return item.oneType === 3
      })

      handleLostItemPicture({ goodFileList: goodFileListData, touristFileList: touristFileListData, paperFileList: paperFileListData })

      if (goodFileListData.length === 0 && touristFileListData.length === 0 && paperFileListData.length === 0) {
        handleLostItemPicVisible(true)
      } else {
        handleLostItemPicManageVisible(true)
      }
    }
  })
  // 新增、编辑遗失物品接口
  const { run: batchUpdateImgR } = useRequest(params => batchUpdateImg(params), {
    manual: true,
    onSuccess: (res, params) => {
      message.success('修改图片成功')
      handleLostItemPicVisible(false)
      handleLostItemPicManageVisible(false)
    },
    onError: (res) => {
      message.error('修改图片失败')
    }
  })

  // 报废年月禁用
  const disabledScrappDate = (current) => {
    return current && current > moment().endOf('month');
  }

  // 多选改变时方法
  const onSelectChange = selectedRowKeys => {
    handleSelectedRowKeys(selectedRowKeys)
  };

  // 多选
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange
  };

  // 清空选择性
  const clearSelection = () => {
    handleSelectedRowKeys([])
  };

  // 新增回调
  const handleAddScrap = async fields => {
    try {
      await addScrap(moment(fields.yearMonth).format('YYYYMM'))
      return true
    } catch (error) {
      message.error('新增失败请重试！');
      return false;
    }
  };

  // 编辑
  const edit = (selectedRows) => {
    if (selectedRows.length === 1) {
      if (selectedRows[0].closeState === 2) {
        message.warning('已结案数据不可修改')
      } else {
        handleScrapNum(selectedRows[0].scrapNumber)
        handleExtendScrapDateVisible(true)
      }
    } else {
      message.warning('请选择一项报废单')
    }
  }

  // 编辑回调
  const handleConfirmScrap = async fields => {
    try {
      await confirmScrap(fields)
      return true
    } catch (error) {
      message.error('编辑失败请重试！');
      return false;
    }
  }

  // 删除
  const del = (selectedRows) => {
    if (selectedRows.length === 0) {
      message.warning('请至少选择一项')
    } else {
      Modal.confirm({
        title: '删除',
        content: '确认删除该数据？',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          let ids = []
          selectedRows.map(item => {
            ids.push(item.scrapNumber)
          })
          deleteScrapLostFormR({ scrapNumbers: ids.join(',') })
        }
      });
    }
  }

  // 查看详情
  const detail = (selectedRows) => {
    if (selectedRows.length !== 1) {
      message.warning('请选择一项报废单')
    } else {
      handleScrapNum(selectedRows[0].scrapNumber)
      handleScrapDetailVisible(true)
    }
  }

  // 结案
  const close = (selectedRows) => {
    if (selectedRows.length === 0) {
      message.warning('请至少选择一项')
    } else {
      let isHaveClose = selectedRows.filter(item => {
        return item.closeState === 2
      })
      if (isHaveClose.length > 0) {
        message.warning('请选择未结案数据')
      } else {
        Modal.confirm({
          title: '结案',
          content: '确认结案该数据？',
          okText: '确认',
          cancelText: '取消',
          onOk: () => {
            let ids = []
            selectedRows.map(item => {
              ids.push(item.scrapNumber)
            })
            closeScrapLostFormR({ scrapNumbers: ids.join(',') })
          }
        });
      }
    }
  }

  // 新增图片/改变图片
  const handleImgs = async fields => {

    let img = []
    let obj = {};

    for (let category in fields) {
      fields[category].forEach(imgInfo => {
        imgInfo.relevance = stateObj.scrapNumber
        img.push(imgInfo)
      })
    }

    // 修改后带有id(原本存在后台)的图片
    let lostItemPicIdArr = img.filter(item => {
      return item.id
    })
    // 新增加的图片
    let lostItemPicNotIdArr = img.filter(item => {
      return !item.id
    })
    // 找到被删除图片加上remark:1
    let updateArr = originPicArr.concat(lostItemPicIdArr).filter(function (v, i, arr) {
      if (arr.indexOf(v) === arr.lastIndexOf(v)) {
        v.remark = 1
      }
      return arr
    });
    // 去重
    updateArr = updateArr.reduce(function (item, next) {
      obj[next.id] ? '' : obj[next.id] = true && item.push(next);
      return item;
    }, []);

    batchUpdateImgR([...updateArr, ...lostItemPicNotIdArr])
  };

  // 删除图片
  const handleDelImgs = async fields => {
    let img = []
    let obj = {};
    for (let category in fields) {
      fields[category].forEach(imgInfo => {
        img.push(imgInfo)
      })
    }

    // 找到被删除图片加上remark:1
    let updateArr = originPicArr.concat(img).filter(function (v, i, arr) {
      if (arr.indexOf(v) === arr.lastIndexOf(v)) {
        v.remark = 1
      }
      return arr
    });
    // 去重
    updateArr = updateArr.reduce(function (item, next) {
      obj[next.id] ? '' : obj[next.id] = true && item.push(next);
      return item;
    }, []);

    batchUpdateImgR(updateArr)
  }

  // 缓存
  useActivate(() => {
    actionRef.current.reload()
  })

  const columns = [
    {
      title: '报废年月',
      dataIndex: 'yearMonth',
      width: 200,
      renderFormItem: (_, { onChange, value, ...rest }) => {
        const format = 'YYYY-MM';
        return (
          <DatePicker.MonthPicker
            onChange={onChange}
            format={format}
            value={value}
            disabledDate={disabledScrappDate}
            {...rest}
          />
        );
      },
      hideInTable: true
    },
    {
      title: '报废单编号',
      dataIndex: 'scrapNumber',
      width: 140,
      hideInSearch: true
    },
    // {
    //   title: '报废日期',
    //   dataIndex: 'scrappDay',
    //   width: 200,
    //   hideInSearch: true
    // },
    {
      title: '图片管理',
      dataIndex: 'picManage',
      width: 200,
      render: (text, record) => (<a onClick={() => {
        if (AuthComponent.getAuth('lostItemManage.lostItemScrapManage.basic')) {
          sessionStorage.setItem(
            '/lostItemManage/lostItemDetail',
            JSON.stringify({ type: 'see', random: Math.random(), scrapNumber: record.scrapNumber })
          )
          getImgByRelevanceR({ relevance: record.scrapNumber })
        }
      }}>图片管理</a>),
      hideInSearch: true
    },
    {
      title: '年',
      dataIndex: 'year',
      width: 120,
      hideInSearch: true
    },
    {
      title: '月',
      dataIndex: 'month',
      width: 120,
      hideInSearch: true
    },
    {
      title: '结案状态',
      dataIndex: 'closeState',
      width: 120,
      render: (text, _) => (
        <div>
          <span>{text === 1 ? '未结案' : ''}</span>
          <span>{text === 2 ? '已结案' : ''}</span>
        </div>
      ),
      hideInSearch: true
    },
    {
      title: '创建日期',
      dataIndex: 'insertTime',
      width: 200,
      hideInSearch: true
    },
    {
      title: '创建人',
      dataIndex: 'createPeople',
      width: 120,
      hideInSearch: true
    },
    {
      title: '结案人',
      dataIndex: 'closePeople',
      width: 120,
      hideInSearch: true
    },
    {
      title: '结案日期',
      dataIndex: 'closeTime',
      width: 120,
      hideInSearch: true
    }
  ];
  return (
    <>
      <ProTable
        actionRef={actionRef}
        formRef={ref}
        rowKey="scrapNumber"
        className={styles.lostItemScrapManage}
        headerTitle={
          <div>
            <span style={{ fontWeight: "700", color: "rgba(0,0,0,0.85)", fontSize: '16px' }}>遗失物品报废数据列表</span>
          </div>
        }
        options={{ fullScreen: true, reload: false, setting: true, density: false }}
        rowSelection={rowSelection}
        search={{
          span: 6
        }}
        toolBarRender={(action, { selectedRows }) => [
          <AuthComponent authCode='lostItemManage.lostItemScrapManage.basic'>
            <Button type="primary" onClick={() => {
              handleScrapListVisible(true)
            }} size="small">
              新增
            </Button>
          </AuthComponent>,
          <AuthComponent authCode='lostItemManage.lostItemScrapManage.edit'>
            <Button type="primary" onClick={() => edit(selectedRows)} size="small">
              修改
            </Button>
          </AuthComponent>,
          <AuthComponent authCode='lostItemManage.lostItemScrapManage.del'>
            <Button type="primary" onClick={() => del(selectedRows)} size="small">
              删除
            </Button>
          </AuthComponent>,
          <AuthComponent authCode='lostItemManage.lostItemScrapManage.basic'>
            <Button type="primary" onClick={() => detail(selectedRows)} size="small">
              查看详情
            </Button>
          </AuthComponent>,
          <AuthComponent authCode='lostItemManage.lostItemScrapManage.basic'>
            <Button type="primary" onClick={() => close(selectedRows)} size="small">
              结案
            </Button>
          </AuthComponent>
        ]}
        tableAlertRender={false}
        request={params => {
          // 请求时清空选择项
          clearSelection()
          return scrapPageList(params)
        }}
        columns={columns}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第${range[0]}-${range[1]}条 共 ${total} 项`,
          defaultPageSize: 20,
          pageSizeOptions: ['20', '30', '40']
        }}
        scroll={{ x: 900, y: 190 }}
      />
      {
        scrapListVisible && <ScrapListForm
          onSubmit={async value => {
            const success = await handleAddScrap(value)
            if (success) {
              message.success('新增成功')
              handleScrapListVisible(false)
              actionRef.current.reload()
            }
          }}
          onCancel={() => handleScrapListVisible(false)}
          scrapListVisible={scrapListVisible}
        ></ScrapListForm>
      }
      {
        extendScrapDateVisible && <ExtendScrapDateTable
          onSubmit={async value => {
            const success = await handleConfirmScrap(value)
            if (success) {
              message.success('编辑成功')
              handleExtendScrapDateVisible(false)
              actionRef.current.reload()
            }
          }}
          scrapNum={scrapNum}
          onCancel={() => handleExtendScrapDateVisible(false)}
          extendScrapDateVisible={extendScrapDateVisible}
        ></ExtendScrapDateTable>
      }
      {
        scrapDetailVisible && <ScrapDetail
          scrapNum={scrapNum}
          onCancel={() => handleScrapDetailVisible(false)}
          scrapDetailVisible={scrapDetailVisible}
        ></ScrapDetail>
      }
      {
        lostItemPicVisible && <PicUpload
          onSubmit={async value => {
            const success = await handleImgs(value)
          }}
          onCancel={() => handleLostItemPicVisible(false)}
          lostItemPicVisible={lostItemPicVisible}
          lostItemPic={lostItemPic}
        ></PicUpload>
      }
      {
        lostItemPicManageVisible && <ShowPic
          onSubmit={async value => {
            const success = await handleDelImgs(value)
          }}
          toUpload={(value) => {
            handleLostItemPicture(value)
            handleLostItemPicManageVisible(false)
            handleLostItemPicVisible(true)
          }}
          onCancel={() => handleLostItemPicManageVisible(false)}
          lostItemPicManageVisible={lostItemPicManageVisible}
          lostItemPic={lostItemPic}
        ></ShowPic>
      }
    </>
  );
};

export default Form.create()(LostItemScrapManage);
